package com.catazzz.springbootstudy.common.elastic;

import com.catazzz.springbootstudy.common.exception.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @作者: Tao
 * @日期: 2025/1/13
 * @时间: 16:34
 * @描述: <br><pre>
 */
@Slf4j
@RestController
@RequestMapping("/elastic")
@Api(tags = "ElasticSearch")
public class ElasticSearchController {

    // 自动注入ArticleRepository接口的实现，用于操作ElasticSearch中的文章数据
    @Autowired
    private ArticleRepository articleRepository;

    /**
     * 新增
     * @param articles 文章列表
     */
    @PostMapping("/create")
    @ApiOperation(value = "新增")
    public Result<Iterable<Article>> create(@RequestBody List<Article> articles) {
        return Result.success(articleRepository.saveAll(articles));
    }


    /**
     * 更新
     * @param article 文章
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新")
    public Result<Article> update(@RequestBody Article article) {
        return Result.success(articleRepository.save(article));
    }

    /**
     * 删除
     * @param id 文章id
     */
    @PutMapping("/delete")
    @ApiOperation(value = "删除")
    public Result<Boolean> delete(@RequestBody long id) {
        articleRepository.deleteById(id);
        return Result.success(Boolean.TRUE);
    }

    /**
     * 根据标题查询
     * @param title 标题
     */
    @GetMapping("/searchByTitle")
    @ApiOperation(value = "根据标题查询")
    public Result<Page<Article>> searchByTitle(@RequestParam String title){
        log.info("title:{}", title);
        PageRequest pageRequest = PageRequest.of(0, 10);

        return Result.success(articleRepository.findByTitleLike(title, pageRequest));
    }
}
